#include "ordersdialog.h"
#include <QVBoxLayout>
#include <QLabel>
OrdersDialog::OrdersDialog(DbConnection *db, UserList *UL, const int&ActionID, const QList<int> &Performers, QWidget *parent) :
    QDialog(parent), m_db(db), m_actionID(ActionID), m_performer(this), m_reports(this), m_content(this)
{
    setWindowTitle(tr("Отчеты об эффективности"));
    QVBoxLayout* main = new QVBoxLayout;
    QHBoxLayout* hlay = new QHBoxLayout;    
    hlay->addWidget(new QLabel(tr("Ответственный за исполнение:")));
    hlay->addWidget(&m_performer);
    hlay->setContentsMargins(0,5,5,15);
    main->addLayout(hlay);
    hlay = new QHBoxLayout;
    QLabel* lb = new QLabel(tr("Отчеты:"));
    lb->setFixedWidth(200);
    hlay->addWidget(lb);
    hlay->addWidget(new QLabel(tr("Содержание:")));
    main->addLayout(hlay);
    hlay = new QHBoxLayout;
    hlay->addWidget(&m_reports);
    m_reports.setFixedWidth(200);
    hlay->addWidget(&m_content);
    main->addLayout(hlay);
    foreach(User* user,UL->users(UserList::All))
        if(Performers.indexOf(user->id())!=-1)
            m_performer.addItem(user->name(),user->id());
    m_performer.model()->sort(0);
    setMinimumWidth(600);
    setMinimumHeight(400);
    setLayout(main);
    connect(&m_reports,SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)),
            this, SLOT(onCurrentItemChange(QListWidgetItem*,QListWidgetItem*)));
    connect(&m_performer,SIGNAL(currentIndexChanged(int)),this,SLOT(performerChanged(int)));
    if(m_performer.count()>0)
    {
        loadReports(m_performer.itemData(0).toInt());
        m_performer.setCurrentIndex(0);
    }
    setWindowIcon(QIcon(":/reports"));
}

void OrdersDialog::loadReports(const int &uid)
{
    DbConnection::QueryResult result = m_db->execute(tr("select * from =schema=.ex_reports where"
                                                        " \"action\"=%1 and \"user\"=%2").arg(m_actionID).arg(uid));
    m_reports.clear();
    m_content.clear();
    if(result.success()&&result.rows()>0)
    {
        for(int i=0;i<result.rows();i++)
        {
            QListWidgetItem* item = new QListWidgetItem(QIcon(":/mark"),result.at(i,3).toString());
            item->setData(Qt::UserRole,result.at(i,4));
            m_reports.addItem(item);
        }
    }
}

void OrdersDialog::performerChanged(const int &index)
{
    loadReports(m_performer.itemData(index).toInt());
}

void OrdersDialog::onCurrentItemChange(QListWidgetItem *current, QListWidgetItem */*previous*/)
{
    if(current!=0)
        m_content.document()->setPlainText(current->data(Qt::UserRole).toString());
}



